package com.kuding.oss;

import static java.util.stream.Collectors.toList;

import java.nio.charset.Charset;
import java.time.Duration;
import java.util.Arrays;
import java.util.Date;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.entity.ContentType;

import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.ObjectMetadata;

public class OssMetaBuilder {

	ObjectMetadata metadata = new ObjectMetadata();

	public static OssMetaBuilder create() {
		return new OssMetaBuilder();
	}

	public OssMetaBuilder contentType(ContentType contentType) {
		metadata.setContentType(contentType.toString());
		return this;
	}

	public OssMetaBuilder cacheControl(CacheControl... cacheControls) {
		String cacheControlStr = String.join(",",
				Arrays.stream(cacheControls).map(x -> x.getValue()).collect(toList()));
		metadata.setCacheControl(cacheControlStr);
		return this;
	}

	public OssMetaBuilder encoding(Charset charset) {
		metadata.setContentEncoding(charset.name());
		return this;
	}

	public OssMetaBuilder expireTime(Duration duration) {
		long milli = duration.toMillis() + System.currentTimeMillis();
		metadata.setExpirationTime(new Date(milli));
		return this;
	}

	public OssMetaBuilder contentMD5(byte[] bs) {
		String md5 = BinaryUtil.toBase64String(DigestUtils.md5(bs));
		metadata.setContentMD5(md5);
		return this;
	}

	public OssMetaBuilder lastModified() {
		metadata.setLastModified(new Date());
		return this;
	}

	public OssMetaBuilder header(String name, String value) {
		metadata.setHeader(name, value);
		return this;
	}

	public ObjectMetadata build() {
		return metadata;
	}
}
